﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services.Protocols;
using System.Web.UI;
using System.Web.UI.WebControls;
using MedicWeb.MedicService;
using MedicWeb.MedRegService;

namespace MedicWeb.forms.Editors.Directory
{
    public partial class InstitutionEdit : SessionPage {
        private Institution institution;

        protected void Page_Load(object sender, EventArgs e){

            string simple = Request.QueryString["simple"];
            string id = Request.QueryString["id"];
            string loc = Request.QueryString["locality"];
            Form.Action = ResolveUrl("~/forms/Editors/Directory/InstitutionEdit.aspx");
            var ms = new MainService();
            var mr = new MedRegService.Service1();
            if (simple != null) {
                Form.Action += "?simple=" + simple;
            }
            if (loc != null) {
                Form.Action += (simple == null ? "?" : "&") + "locality="+loc;
            }
            if (id != null) {
                Form.Action += ((simple == null && loc == null) ? "?" : "&") + "id=" + id;
                institution = ms.LoadInstitution(GetSession(), int.Parse(id));
            } else {
                institution = new Institution();
                if (loc != null) {
                    institution.Locality = ms.LoadLocality(GetSession(), Convert.ToInt32(loc));
                }
                institution.Ownership = new Ownership();
                institution.InstitutionType = new InstitutionType();
            }
            if (institution.Locality == null) {
                institution.Locality = new Locality() { Region = new Region() };
            }
            if (institution.Locality.Region == null) {
                institution.Locality.Region = new Region();
            }
            ////////////////////////////////////////////////////////////////////////////////////////////////////////                
            ////////////////////////////////////////////////////////////////////////////////////////////////////////                
            comboMedReGLPU.Items.Add(new ListItem("- Не выбрано -", "" + Guid.Empty));
            foreach (var lpu in mr.GetFlatLPUList()) {
                var listItem = new ListItem(lpu.Name, "" + lpu.ID);
                listItem.Attributes["type"] = lpu.GetType().Name;
                comboMedReGLPU.Items.Add(listItem);
            }
            ////////////////////////////////////////////////////////////////////////////////////////////////////////
            ////////////////////////////////////////////////////////////////////////////////////////////////////////                

            comboRegion.Enabled = simple == null || !bool.Parse(simple);
            comboLocality.Enabled = simple == null || !bool.Parse(simple);

            if (!IsPostBack) {
                tfTitle.Text = institution.Title;
                tfPhone.Text = institution.InstitutionPhone;
                tfAddress.Text = institution.InstitutionAddress;
                FillCombo(comboType, ms.GetInstitutionTypeList(GetSession(), false), institution.InstitutionType);
                FillCombo(comboOwnership, ms.GetOwnershipList(GetSession(), false), institution.Ownership);

                Locality locality = institution.Locality;
                if (institution.Id != 0) {
                    Region region = locality.Region;
                    FillCombo(comboRegion, ms.GetRegionList(GetSession(), false), region);
                    FillCombo(comboLocality, ms.GetLocalityList(GetSession(), false), locality);
                    hfLocality.Value = "" + locality.Id;
                } else {
                    FillCombo(comboRegion, ms.GetRegionList(GetSession(), false), locality.Region);
                    FillCombo(comboLocality, ms.GetLocalityList(GetSession(), false), locality);
                    hfLocality.Value = ""+locality.Id;
                }
                if (loc != null) {
                    comboRegion.Enabled = false;
                    comboLocality.Enabled = false;
                }
                comboMedReGLPU.SelectedValue = "" + institution.Rmr;
            }
        }

        private static void FillCombo(ListControl combo, IEnumerable<DirectorySimpleItem> items, DirectorySimpleItem selectedValue) {
            foreach (var item in items) {
                var listItem = new ListItem(item.Title, "" + item.Id);
                listItem.Attributes["type"] = item.GetType().Name;
                combo.Items.Add(listItem);
            }
            SelectInCombo(combo, selectedValue);
        }

        private static void FillCombo(ListControl combo, IEnumerable<Locality> items, Locality selectedValue) {
            combo.Items.Add(new ListItem("Не выбран", "0"));
            foreach (var item in items) {
                var listItem = new ListItem(item.Title, "" + item.Id);
                listItem.Attributes["region"] = "" + item.Region.Id;
                listItem.Attributes["type"] = item.GetType().Name;
                combo.Items.Add(listItem);
            }
            SelectInCombo(combo, selectedValue);
        }

        private static void SelectInCombo(ListControl combo, DirectorySimpleItem selectedValue) {
            if (selectedValue != null) {
                try {
                    combo.SelectedValue = "" + selectedValue.Id;
                } finally { }
            }
        }

        protected void btnSave_Click(object sender, EventArgs e) {
            try {
                var ms = new MainService();
                institution.InstitutionAddress = tfAddress.Text;
                institution.InstitutionPhone = tfPhone.Text;
                institution.InstitutionType.Id = Convert.ToInt32(comboType.SelectedValue);
                institution.Locality.Id = Convert.ToInt32(hfLocality.Value);
                institution.Ownership.Id = Convert.ToInt32(comboOwnership.SelectedValue);
                institution.Title = tfTitle.Text;
                institution.Rmr = new Guid(comboMedReGLPU.SelectedValue);
                institution = ms.SaveInstitution(GetSession(), institution);
                Session["success"] = "Изменения сохранены успешно";
            } catch (Exception ex) {

                if (ex.InnerException is SoapException
                    && ((SoapException)ex.InnerException).Detail.InnerText == "AuthorizationException") {
                    throw ex;
                } else {
                    Session["error"] = "Ошибка сохранения";
                }
            }
        }
    }
}